package org.stone.project.tx.utils;

import cn.hutool.extra.spring.SpringUtil;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

@Component
public class UserLockUtil {
    @PostConstruct
    public void init(){
        RedissonClient redissonClient = SpringUtil.getBean(RedissonClient.class);
        UserLockUtil.redissonClient = redissonClient;
    }

    private static RedissonClient redissonClient;

    private static String clusterTXPrefix="CLUSTER_TX_PREFIX:";

    public static RLock lockUser(String userId) throws InterruptedException {
        RLock lock = redissonClient.getLock(clusterTXPrefix + userId);
        lock.tryLock(5, TimeUnit.SECONDS);
        return lock;
    }
}
